package com.leetcode.No0811;

import org.junit.Test;

import java.util.*;

/**
 * @program: Solution
 * @description: 子域名访问计数
 * @author: Wang Zhihua
 * @date: 2022-10-11
 */
public class Solution {
    public List<String> subdomainVisits(String[] cpdomains) {
        Map<String, Integer> map = new HashMap<>();

        for (String cpdomain : cpdomains) {
            String[] data = cpdomain.split(" ");
            int times = Integer.parseInt(data[0]);
            String[] urls = data[1].split("\\.");
            int urlsLen = urls.length;
            for (int i = urlsLen - 2; i >= 0; --i) {
                urls[i] += "." + urls[i + 1];
            }
            for (String url : urls) {
                Integer t = map.get(url);
                if (Objects.isNull(t)) {
                    map.put(url, times);
                } else {
                    map.put(url, t + times);
                }
            }
        }


        Set<String> urlSet = map.keySet();
        List<String> ansList = new ArrayList<>(urlSet.size());
        for (String url : urlSet) {
            Integer t = map.get(url);
            ansList.add(t + " " + url);
        }

        return ansList;
    }

    @Test
    public void test1() {
        String[] cpdomains = new String[]{"9001 discuss.leetcode.com"};
        System.out.println(subdomainVisits(cpdomains));

        cpdomains = new String[]{"900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"};
        System.out.println(subdomainVisits(cpdomains));
    }
}
